package v1

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/pkg/errors"
	"strconv"
	"strings"
	"zimuzu_cvn_web_api/config"
	"zimuzu_cvn_web_api/model"
	"zimuzu_cvn_web_api/pkg/e"
	"zimuzu_cvn_web_api/pkg/errno"
	"zimuzu_cvn_web_api/router/api"
	"zimuzu_cvn_web_api/router/api/app/middleware"
	"zimuzu_cvn_web_api/service"
)

type AgentAPI struct {
}

func (a AgentAPI) Name() string {
	return "agent API"
}

func (a AgentAPI) Bind() {
	agentAuthAPI := config.C.Router.Group("/v1/app/agent", middleware.TrackLog(), middleware.AuthMiddleware())
	{
		agentAuthAPI.GET("info", info)
		agentAuthAPI.GET("isShow", isShow)
		agentAuthAPI.POST("updateInfo", updateInfo)
		agentAuthAPI.GET("viewInfo", viewAgentInfo)
		agentAuthAPI.GET("priceForm", priceForm)
		agentAuthAPI.GET("codeInfo", codeInfo)
		agentAuthAPI.GET("codeList", codeList)
		agentAuthAPI.GET("updateCodeStatus", updateCodeSaleStatus)
		agentAuthAPI.GET("packageList", packageList)
		agentAuthAPI.POST("exchange", exchange)
		agentAuthAPI.GET("upgradeList", upgradeList)
		agentAuthAPI.GET("rank", agentRank)
		agentAuthAPI.POST("payOrder", payOrder)
		agentAuthAPI.GET("orderList", orderList)
		agentAuthAPI.GET("apply", apply)
		agentAuthAPI.GET("upgrade", upgrade)
	}

	agentAPI := config.C.Router.Group("/v1/app/agent", middleware.TrackLog())
	{
		agentAPI.GET("topAgent", topAgent)
	}
}

/*
 * @ Author: hupfei
 * @ Description: 3.12.1 经销商信息
 **/
func info(c *gin.Context) {
	uid, _ := service.GetUserIdByRequest(c)
	info, err := service.GetAgentInfo(uid)
	if err != nil {
		api.SendResponse(c, errors.New("获取经销商信息失败"), nil)
		return
	}

	errno.OK.Info = "获取经销商信息成功"
	api.SendResponse(c, errno.OK, info)
	return
}

/*
 * @ Author: hupfei
 * @ Description: 3.12.2 更新是否在排行榜中展示
 **/
type isShowParams struct {
	Show int `form:"show"` //1展示  0取消展示
}

func isShow(c *gin.Context) {
	var params isShowParams
	err := c.ShouldBindWith(&params, binding.Query)
	if err != nil {
		api.SendResponse(c, errno.ParamsError, nil)
		return
	}

	uid, _ := service.GetUserIdByRequest(c)
	err = model.UpdateAgentShowStatus(uid, params.Show)
	if err != nil {
		api.SendResponse(c, errors.New("更新是否在排行榜中展示失败"), nil)
		return
	}

	errno.OK.Info = "更新是否在排行榜中展示成功"
	api.SendResponse(c, errno.OK, nil)
	return
}

/*
 * @ Author: hupfei
 * @ Description: 3.12.3 更新经销商联系方式
 **/
type updateInfoParams struct {
	Wechat string `form:"wechat"`
	Email  string `form:"email"`
}

func updateInfo(c *gin.Context) {
	var params updateInfoParams
	err := c.ShouldBindWith(&params, binding.FormPost)
	if err != nil {
		api.SendResponse(c, errno.ParamsError, nil)
		return
	}

	if len(params.Email) > 0 && !e.IsEmail(params.Email) {
		api.SendResponse(c, errors.New("邮箱格式不正确"), nil)
		return
	}

	if len(params.Wechat) > 0 && !e.IsWechat(params.Wechat) {
		api.SendResponse(c, errors.New("微信号格式不正确"), nil)
		return
	}

	uid, _ := service.GetUserIdByRequest(c)
	err = model.UpdateAgentContactInfo(uid, params.Wechat, params.Email)
	if err != nil {
		api.SendResponse(c, errors.New("更新失败"), nil)
		return
	}

	errno.OK.Info = "更新成功"
	api.SendResponse(c, errno.OK, nil)
	return
}

/*
 * @ Author: hupfei
 * @ Description: 3.12.4 会员购买排行榜
 **/
type agentRankParams struct {
	model.PageParams
	Source int `form:"source"` //0 新人榜  1 品质榜
}

func agentRank(c *gin.Context) {
	var params agentRankParams
	params.PageParams = model.NewDefaultPageParams()
	err := c.ShouldBindWith(&params, binding.Query)
	if err != nil {
		api.SendResponse(c, errno.ParamsError, nil)
		return
	}

	info, err := service.AgentRank(params.Page, params.Per, params.Source)
	if err != nil {
		api.SendResponse(c, errors.New("查询会员购买排行榜失败"), nil)
		return
	}

	errno.OK.Info = "查询会员购买排行榜成功"
	api.SendResponse(c, errno.OK, info)
	return
}

/*
 * @ Author: hupfei
 * @ Description: 3.12.5查看经销商资料
 **/
type viewAgentInfoParams struct {
	Uid int64 `form:"uid" binding:"required"`
}

func viewAgentInfo(c *gin.Context) {
	var params viewAgentInfoParams
	err := c.ShouldBindWith(&params, binding.Query)
	if err != nil {
		api.SendResponse(c, errno.ParamsError, nil)
		return
	}

	uid, _ := service.GetUserIdByRequest(c)
	info, err := service.ViewAgentInfo(uid, params.Uid)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}

	errno.OK.Info = "查看经销商资料成功"
	api.SendResponse(c, errno.OK, info)
	return
}

func topAgent(c *gin.Context) {
	info, err := model.GetTopAgentInfoList()
	if err != nil {
		api.SendResponse(c, errors.New("查询失败"), nil)
		return
	}

	var res []model.TopAgentInfo
	for _, user := range info {
		//昵称隐藏
		user.Name = e.NicknameFormat(user.Name)
		res = append(res, user)
	}

	errno.OK.Info = "查询成功"
	api.SendResponse(c, errno.OK, res)
	return
}

/*
 * @ Author: hupfei
 * @ Description: 3.12.10 经销商会员价格拿价单
 **/
func priceForm(c *gin.Context) {
	info, err := service.PriceForm()
	if err != nil {
		api.SendResponse(c, errors.New("查看经销商会员价格失败"), nil)
		return
	}

	errno.OK.Info = "查看经销商会员价格成功"
	api.SendResponse(c, errno.OK, info)
	return
}

/*
 * @ Author: hupfei
 * @ Description: 3.12.11 我的升级码信息
 **/
func codeInfo(c *gin.Context) {
	uid, _ := service.GetUserIdByRequest(c)
	info, err := service.GetUpgradeCodeInfo(uid)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}

	errno.OK.Info = "查看升级码信息成功"
	api.SendResponse(c, errno.OK, info)
	return
}

/*
 * @ Author: hupfei
 * @ Description: 3.12.12 升级码列表
 **/
type codeListParams struct {
	model.PageParams
	Peroid int `form:"peroid"`
	Sale   int `form:"sale"`
}

func codeList(c *gin.Context) {
	var params codeListParams
	params.PageParams = model.NewDefaultPageParams()
	err := c.ShouldBindWith(&params, binding.Query)
	if err != nil {
		api.SendResponse(c, errno.ParamsError, nil)
		return
	}

	uid, _ := service.GetUserIdByRequest(c)

	info, err := model.GetUpgradeCodeList(uid, params.Peroid, params.Sale, params.Page, params.Per)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}

	errno.OK.Info = "查看升级码列表成功"
	api.SendResponse(c, errno.OK, info)
	return
}

/*
 * @ Author: hupfei
 * @ Description: 3.12.13更新升级码状态
 **/
type updateCodeStatusParams struct {
	Sale int    `form:"sale"`
	Id   string `form:"id" binding:"required"`
}

func updateCodeSaleStatus(c *gin.Context) {
	var params updateCodeStatusParams
	err := c.ShouldBindWith(&params, binding.Query)
	if err != nil {
		api.SendResponse(c, errno.ParamsError, nil)
		return
	}

	var nodeIds []int64
	_ = json.Unmarshal([]byte(params.Id), &nodeIds)
	if len(nodeIds) == 0 {
		api.SendResponse(c, errors.New("参数异常"), nil)
		return
	}
	// 超过50个只处理前50个数据
	if len(nodeIds) > 50 {
		api.SendResponse(c, errors.New("一次最多只能更新50条数据"), nil)
		return
	}

	uid, _ := service.GetUserIdByRequest(c)

	params.Id = strings.Replace(params.Id, "[", "", -1)
	params.Id = strings.Replace(params.Id, "]", "", -1)

	row, err := model.UpdateUpgradeCodeSaleStatus(uid, params.Sale, params.Id)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}

	if row != int64(len(nodeIds)) {
		info := "批量更新失败:其中成功{" + strconv.FormatInt(row, 10) + "}条，失败{" + strconv.FormatInt(int64(len(nodeIds))-row, 10) + "}条。"
		api.SendResponse(c, errors.New(info), nil)
		return
	}
	errno.OK.Info = "更新升级码售卖状态成功"
	api.SendResponse(c, errno.OK, nil)
	return
}

type packageListParams struct {
	GoodsId int `form:"goodsId" binding:"required"`
}
type packageListReturn struct {
	CodeExpire int                           `json:"codeExpire"`
	Package    []service.CurrentPackagePrice `json:"package"`
}

//查询经销商商品套餐价格信息
//Auth: Xu
func packageList(c *gin.Context) {
	var params packageListParams
	err := c.ShouldBindWith(&params, binding.Query)
	if err != nil {
		api.SendResponse(c, errno.ParamsError, nil)
		return
	}
	uid, _ := service.GetUserIdByRequest(c)
	packageList, err := service.GetGoodsPackageList(uid, params.GoodsId)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}
	returnData := packageListReturn{
		CodeExpire: service.CodeExpire,
		Package:    packageList,
	}
	errno.OK.Info = "查询成功"
	api.SendResponse(c, errno.OK, returnData)
	return
}

type exchangeParams struct {
	PackageId int `form:"packageId" binding:"required"`
}

//兑换金至尊会员下单
//Auth: Xu
func exchange(c *gin.Context) {
	api.SendResponse(c, errno.FunctionClose, nil)
	return
	var params exchangeParams
	err := c.ShouldBindWith(&params, binding.FormPost)
	if err != nil {
		api.SendResponse(c, errno.ParamsError, nil)
		return
	}
	uid, _ := service.GetUserIdByRequest(c)
	orderInfo, err := service.ExchangeVip(uid, params.PackageId)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}
	errno.OK.Info = "下单成功"
	api.SendResponse(c, errno.OK, orderInfo)
	return
}

type payOrderParams struct {
	OrderNo string `form:"orderNo" json:"orderNo" binding:"required,excludes=  "`
	U       string `form:"u" json:"u" binding:"required,excludes= "`
}

//兑换金至尊订单支付
//Auth: Xu
func payOrder(c *gin.Context) {
	api.SendResponse(c, errno.FunctionClose, nil)
	return
	var params payOrderParams
	err := c.ShouldBindWith(&params, binding.FormPost)
	if err != nil {
		api.SendResponse(c, errno.ParamsError, nil)
		return
	}
	uid, _ := service.GetUserIdByRequest(c)
	//userInfo, err := service.GetUserInfo(uid)
	//if err != nil{
	//	api.SendResponse(c, err, nil)
	//	return
	//}
	//if errValid := service.ValidateCode(userInfo.PhoneNumber , service.SendCodeSceneReg, params.Code); errValid != nil{
	//	api.SendResponse(c, errValid, nil)
	//	return
	//}
	ok := service.IsPayPasswordChecked(uid, params.U)
	if !ok {
		api.SendResponse(c, errno.SignError, nil)
		return
	}
	err = service.PayOrder(params.OrderNo, uid)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}

	errno.OK.Info = "支付成功"
	api.SendResponse(c, errno.OK, nil)
	return
}

type orderListParams struct {
	Date string `form:"date" binding:"required,excludes= "`
}

// 兑换历史列表
func orderList(c *gin.Context) {
	var params orderListParams
	err := c.ShouldBindWith(&params, binding.Query)
	if err != nil {
		api.SendResponse(c, errno.ParamsError, nil)
		return
	}
	uid, _ := service.GetUserIdByRequest(c)
	orderList, err := service.GetGoodsOrderList(uid, params.Date)

	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}
	errno.OK.Info = "ok"
	api.SendResponse(c, errno.OK, orderList)
	return

}

// 查询可升级列表
// Auth:hzp
func upgradeList(c *gin.Context) {

	uid, _ := service.GetUserIdByRequest(c)
	list, err := service.GetAgentUpgradeList(uid)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}
	errno.OK.Info = "查询成功"
	api.SendResponse(c, errno.OK, list)
	return
}

type upgradeParams struct {
	Type int    `form:"type" binding:"required"`
	From int    `form:"from" binding:"required"`
	U    string `form:"u" binding:"required,excludes= "`
}

// 升级会员经销商
// Auth:hzp
func upgrade(c *gin.Context) {
	api.SendResponse(c, errno.FunctionClose, nil)
	return
	var params upgradeParams
	err := c.ShouldBindWith(&params, binding.Query)
	if err != nil {
		api.SendResponse(c, errno.ParamsError, nil)
		return
	}
	uid, _ := service.GetUserIdByRequest(c)

	// 校验u
	ok := service.IsPayPasswordChecked(uid, params.U)
	if !ok {
		api.SendResponse(c, errno.SignError, nil)
		return
	}

	// 升级
	err = service.AgentUpgrade(uid, params.From, params.Type)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}

	errno.OK.Info = "升级成功"
	api.SendResponse(c, errno.OK, nil)
	return
}

type applyParams struct {
	Type int    `form:"type" binding:"required"`
	U    string `form:"u" binding:"required"`
}

// 申请会员经销商
// Auth:hzp
func apply(c *gin.Context) {
	api.SendResponse(c, errno.FunctionClose, nil)
	return
	var params applyParams
	err := c.ShouldBindWith(&params, binding.Query)
	if err != nil {
		api.SendResponse(c, errno.ParamsError, nil)
		return
	}
	uid, _ := service.GetUserIdByRequest(c)

	// 校验u
	ok := service.IsPayPasswordChecked(uid, params.U)
	if !ok {
		api.SendResponse(c, errno.SignError, nil)
		return
	}

	// 申请
	data, err := service.AgentApply(uid, params.Type)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}

	errno.OK.Info = "申请成功"
	api.SendResponse(c, errno.OK, data)
	return
}
